package com.ruoyi.pay.service;


import com.github.wxpay.sdk.WXPayUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.pay.result.Result;
import okhttp3.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WXPayService {



    /*
    weixin:
      appid: wxab8acb865bb1637e
      partner: 11473623
      partnerkey: 2ab9071b06b9f739b950ddb41db2690d
      notifyurl:  http://wk9k36.natappfree.cc/api/wxpay/notify_url
     */
    @Value("${weixin.appid}")
    String appid;
    @Value("${weixin.partner}")
    String partner;
    @Value("${weixin.partnerkey}")
    String partnerkey;
    @Value("${weixin.notifyurl}")
    String notifyurl;
    /**
     * 完成对微信 NATIVE  统一下单接口的封装
     * @param orderId
     * @param totalFee
     */
    public AjaxResult unifiedOrder(Long orderId, Integer totalFee,String body) throws Exception {
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();//POSTman

        Map map = new HashMap<>();
        map.put("appid",appid);
        map.put("mch_id",partner);
        map.put("nonce_str", WXPayUtil.generateNonceStr());//nonce  number once
        map.put("body", body);
        map.put("out_trade_no", String.valueOf(orderId));
        map.put("total_fee", String.valueOf(totalFee));
        map.put("spbill_create_ip", "127.0.0.1");
        map.put("notify_url", notifyurl);//
        map.put("trade_type", "NATIVE");

        String sign = WXPayUtil.generateSignature(map, partnerkey);
        map.put("sign", sign);
        String requestBodyXml = WXPayUtil.mapToXml(map);

        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/xml"),
                requestBodyXml);
        Request request = new Request.Builder()
                .url("https://api.mch.weixin.qq.com/pay/unifiedorder") //URL
                .addHeader("Content-Type", "application/xml")
                .post(requestBody)//POST   requestBody
                .build();
        //点击 发送

        Response response = okHttpClient.newCall(request).execute();
        System.out.println("successful = " + response.isSuccessful());
        System.out.println("code = " + response.code());//200
        System.out.println("message = " + response.message());//OK
        System.out.println("headers = " + response.headers());

        String responseBody_xml = response.body().string();

        System.out.println(responseBody_xml);

        Map<String, String> responseBodyMap = WXPayUtil.xmlToMap(responseBody_xml);

        String return_code = responseBodyMap.get("return_code");
        String return_msg = responseBodyMap.get("return_msg");
        if(return_code.equalsIgnoreCase("SUCCESS")){
            String result_code = responseBodyMap.get("result_code");
            String err_code_des = responseBodyMap.get("err_code_des");
            if(result_code.equalsIgnoreCase("SUCCESS")){
                String code_url = responseBodyMap.get("code_url");
                return  new AjaxResult(200,"ok",code_url);
            }else{
                return  new AjaxResult(400,"false",err_code_des);
            }
        }

        return  new AjaxResult(400,"false",return_msg);
    }




}
